<?php
//error_reporting(E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR);
require('./roots.php');
require($root_path.'include/inc_environment_global.php');

define('LANG_FILE','aufnahme.php');
$local_user='aufnahme_user';
require_once($root_path.'include/inc_front_chain_lang.php');
require_once($root_path.'include/inc_date_format_functions.php');
require_once($root_path.'classes/datetimemanager/class.dateTimeManager.php');

//Importacion y creacion de instancia de la clase queries_data_search
$filename = $root_path."db/interconsulta/queries_data_search.php";
require_once($filename);
$query_data_search = new Queries_data_search();

# Create time manager object
$datetime_obj= & new dateTimeManager;

$thisfile=basename(__FILE__);
$searchmask_bgcolor="#f3f3f3";
$searchprompt=$LDEnterSearchKeyword;

$quicklistmaxnr=10; // The maximum number of quicklist popular items

# Uncomment the following to debug the sql queries
//$db->debug=1;

$sql='';

if(!isset($mode)) $mode='';

# Set limited query result to false as default
$limitselect=FALSE;

# Set the default name of of the form
# Note to Jean-Philippe LIOT
# the form name was moved outside of the sql query because otherwise the element names become too long and get pruned by PostgreSQL

$formname ='regform';

if(isset($target)) {
   switch ($target)
	{
		case 'paciente' :
                    //$sql="SELECT DISTINCT p.pid AS \"id_paciente.value\", p.name_last AS \"apellido_1.value\", p.name_2 AS \"apellido_2.value\", p.name_first AS \"name_1.value\", p.name_middle AS \"name_2.value\", p.sex AS \"sex\", p.ethnic_orig AS \"etnia.value\", 0 AS use_frequency FROM care_person p";
                    if($mode=='search') {
						$sql = $query_data_search->select_care_person($searchkey);                  
                        //$sql.=" WHERE p.name_first $sql_LIKE '$searchkey%' OR p.name_last $sql_LIKE '$searchkey%' OR p.nat_id_nr $sql_LIKE '$searchkey%'";
                        }else {
						$sql = $query_data_search->select_care_person_order();                  
                        //$sql.=" ORDER BY p.pid DESC";
                        $limitselect=TRUE;
                    }
                    $title=$LDSearch.' :: '.$LDPatient.' ('.$LDPatient.')';
                    $itemname=$LDPatient;
                    $formname='regform';
		    $lange=$lang;
                    break;
        case 'grupo':
            //$sql="SELECT DISTINCT nombre AS \"nombre.value\" FROM care_interconsulta_grupo_triaje";
            if($mode=='search') {
				$sql = $query_data_search->select_care_interconsulta_grupo($searchkey);
				// se agrega el where a dicha consulta, ya que antes no tenia dicho comando
                //$sql.="where nombre $sql_LIKE '$searchkey%'";
            } 
            else {
				$sql = $query_data_search->select_care_interconsulta_grupo_order();
                //$sql.=" ORDER BY nombre DESC";
                $limitselect=TRUE;
            }

            $title=$LDSearch.' :: '.$LDInter.' (Grup)';
            $itemname=$LDGrupo;
            $formname='regform';
	    $lange=$lang;
            break;
        case 'usuario':
            //$sql="SELECT DISTINCT login_id AS \"login_id.value\" FROM care_users";
            if($mode=='search') {
                //$sql.=" WHERE login_id $sql_LIKE '%$searchkey%' or name $sql_LIKE '%$searchkey%' ";
                $sql = $query_data_search->select_login_care_users($searchkey);
            } 
            else {
                //$sql.=" ORDER BY login_id DESC";
                $sql = $query_data_search->select_login_care_users_order();
                $limitselect=TRUE;
            }

            $title=$LDSearch.' :: '.$LDInter.' (Usr)';
            $itemname=$LDUser;
            $formname='regform';
	    $lange=$lang;
            break;
	}
	
	# The adodb function of limited nr of return query is now used here
//   echo $sql;

	if($limitselect){
		if($result=$db->SelectLimit($sql,$quicklistmaxnr)){
			$linecount=$result->RecordCount();
		}
	}else{
		if($result=$db->Execute($sql)){
			$linecount=$result->RecordCount();
		}
	}
	if($linecount) $sql_value=$result->GetArray();
}

/* Set color values for the search mask */
$entry_block_bgcolor='#fff3f3';
$entry_border_bgcolor='#66ee66';
$entry_body_bgcolor='#ffffff';
?><?php html_rtl($lang); ?>
<head>
<?php echo setCharSet(); ?>
<title><?php echo $title; echo $lange;?></title>


<script language="javascript">

var http_request = false;
   function makePOSTRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert("<?php echo $LDHttpInsta; ?>");
         return false;
      }

      http_request.onreadystatechange = alertContents;
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
   }

   function alertContents() {
//     //alert("entrando en alertcontents");
//     if(!(http_request))
//     {
//         alert("es null");
//     }
//     else
//     {
        //alert("no es null");
    
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            eval(http_request.responseText);
         } else {
            alert("<?php echo $LDHttpReque; ?>");
         }
      }
    //}
   }


function setValue(val) {
	mywin=parent.window.opener;
	var array_val= val.split("|");
	<?php
	$var_parent_document=array_keys($sql_value[0]);
	$indice=0;

	for($i3=1;$i3<sizeof($var_parent_document)-1;$i3=$i3+2) 
	{ 
		echo 'mywin.document.'.$formname.'.'.$var_parent_document[$i3].'=array_val['.$indice.']; '; 
		$indice++;
	};


        if (!strcmp($target, 'paciente'))
        {
	?>
		if(array_val[5]=='m'){//Para setear el sexo
			mywin.document.regform.sexo_paciente_m.checked = true;
	
		}
                else if(array_val[5]=='f'){
			mywin.document.regform.sexo_paciente_f.checked = true;
		}
                //mywin.document.regform.etnia.selectedIndex = array_val[6];

                for (n=0;n<mywin.document.regform.etnia.length;n++)
                {
                    if (mywin.document.regform.etnia[n].value == array_val[6])
                    {
                        mywin.document.regform.etnia.selectedIndex = n;
                        break;
                    }
                }


		this.window.close();
		mywin.focus();
	<?php
       	}

	if (!strcmp($target, 'grupo'))
        {
            echo 'mywin.document.'.$formname.'.'.$var_parent_document[1].'=array_val[0]; '; 
            echo "mywin.document.$formname.noasig.options.length=0;";
            echo "mywin.document.$formname.asig.options.length=0;";
            echo "makePOSTRequest('ajax-usutriaje.php','val=' + val + '&formname=$formname'+'&lange=$lange');";
        }
        else if (!strcmp($target, 'usuario'))
        {
            echo 'mywin.document.'.$formname.'.'.$var_parent_document[1].'=array_val[0];';
	    echo "\n";
            echo "mywin.document.$formname.noasig.options.length=0;";
	    echo "\n";
            echo "mywin.document.$formname.asig.options.length=0;";
	    echo "\n";
            echo "makePOSTRequest('ajax-espeusuario.php','val=' + val + '&formname=$formname'+'&lange=$lange');";
	    echo "\n";
        }

	?>
	setTimeout("this.window.close()", 1000);
	//this.window.close();
	mywin.focus();
}

</script>
</head>
<body><font face=arial>

<font size=3><b><?php echo $title ?></b></font>

		 <table border=0 cellpadding=10 bgcolor="<?php echo $entry_border_bgcolor ?>">
     <tr>
       <td>
            <input type="hidden" id="hidval" value=""/>
<?php   
include($root_path.'include/inc_patient_searchmask.php');

?>
</td>
     </tr>
   </table>

<?php
if($mode=='search')  {
    if(!$linecount) $linecount=0;
    echo '<hr width=80% align=left>'.str_replace("~nr~",$linecount,$LDSearchFoundData).'<p>';
} else {
    echo '<hr width=80% align=left><font size=4 color="#990000">'.$LDTop.' '.$quicklistmaxnr.' '.$LDQuickList.'</font>';
}

    //echo $mode;
    if ($linecount) 
	{ 
         $count=0;
	 					echo '
						<table border=0 cellpadding=2 cellspacing=1> 
						<tr bgcolor="#66ee66" background="'.$root_path.'gui/img/common/default/tableHeaderbg.gif">';

                        if (strcmp($target, 'grupo') && strcmp($target, 'usuario'))
                        {
                            echo '
                            <td><font face=arial size=2 color="#336633"><b>Id. '.$itemname.'</b></td>';
                        }

                        echo '
                            <td><font face=arial size=2 color="#336633"><b>'.$LDnombreSolo.$itemname.'</b></td>';

						echo '
						<td><font face=arial size=2 color="#336633">&nbsp;</td>';



					echo "</tr>";
					$sql_value_without_key=array_values($sql_value);
					for($i=0;$i<sizeof($sql_value);$i++)
					{
					    if(($mode!='search')&&($count==$quicklistmaxnr)) break;
						    else $count++;
							
						echo "
							<tr bgcolor=";
						if($toggle) { echo "#efefef>"; $toggle=0;} else {echo "#ffffff>"; $toggle=1;};

                        echo "<td><font face=arial size=2>";
                        if (strcmp($target, 'grupo') && strcmp($target, 'usuario'))
                        {
                            echo "&nbsp;".$sql_value[$i][0];
                            echo "</td>";
                            echo "<td><font face=arial size=2>";
                            echo "&nbsp;".$sql_value[$i][1].", ".$sql_value[$i][3];
                            echo "</td>";
                        }
                        else
                        {
                            echo "&nbsp;".$sql_value[$i][0];
                            echo "</td>";
                        }

						if(isset($sql_value_without_key[$i]['refresh_date.value']) && !empty($sql_value_without_key[$i]['refresh_date.value'])){

							$shifted_date=$datetime_obj->shift_dates(date('Y-m-d'),-($sql_value_without_key[$i]['refresh_date.value']),'d');

							$sql_value_without_key[$i]['refresh_date.value']=formatDate2Local($shifted_date,$date_format);
						}

						$sql_java_string='';
						while(list($x,$v)=each($sql_value_without_key[$i])){
							if(is_integer($x)) continue;
								else $sql_java_string.="$v|";
						}


						echo "<td><font face=arial size=2>";
						echo '<a href="javascript:setValue(\''.$sql_java_string.'\')">';
						echo '<img '.createLDImgSrc($root_path,'ok_small.gif','0').' alt="'.$LDTestThisPatient.'"></a>&nbsp;';
						echo '</td></tr>';
					}
					echo "
						</table>";
					if($mode=='search' && $linecount>15)
					{
?>
         <p>
		 <table border=0 cellpadding=10 bgcolor="<?php echo $entry_border_bgcolor ?>">
     <tr>
       <td>
	   <?php
	   
	        $searchform_count=2;
            include($root_path.'include/inc_patient_searchmask.php');
       
	   ?>
</td>
     </tr>
   </table>
<?php
				}
    }
?>
</font>
</body>
</html>
